<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let users = [
        { name: "John", age: 20, surname: "Johnson" },
        { name: "Pete", age: 18, surname: "Peterson" },
        { name: "Ann", age: 19, surname: "Hathaway" },
      ];
      function byField(v) {
        return function (a, b) {
          return a[v] > b[v] ? 1 : -1;
        };
      }
      users.sort(byField("name"));
      console.log(users);
      // users.sort(byField("age"));
      // 通常的做法应该是这样的
      // users.sort((a, b) => (a.name > b.name ? 1 : -1)); // 通过 name (Ann, John, Pete)
      // users.sort((a, b) => (a.age > b.age ? 1 : -1)); // 通过 name (Ann, John, Pete)
      // 可以让它更加简洁吗，比如这样？
    </script>
  </body>
</html>
